<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Download, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import UserBloodSugarRecords from './BloodSugar.vue'
import axios from "axios";

// 查询参数
const queryParams = reactive({
  userAccount: '',
  bloodSugarStatus: '0',
  beginBloodSugar: '0.0',
  endBloodSugar: '0.0',
})

// 血糖状态选项
const bloodSugarStatusTypeOptions = [
  { value: '0', label: '全部' },
  { value: '1', label: '正常' },
  { value: '2', label: '低血糖' },
  { value: '3', label: '高血糖' }
]

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

//弹窗框相关
const recordDialogVisible = ref(false)
const currentUser = reactive({
  id: '',
  username: '',
  nickname: ''
})

// 获取血糖状态标签
const getBloodSugarStatus = (value) => {
  if (value < 3.9) return { type: 'danger', label: '低血糖', status: 2 }
  if (value >= 7.0) return { type: 'danger', label: '高血糖', status: 3 }
  if (value >= 5.6) return { type: 'warning', label: '偏高', status: 1 }
  return { type: 'success', label: '正常', status: 1 }
}

// 获取血糖显示样式
const getSugarClass = (value) => {
  if (value < 3.9) return 'hypoglycemia'
  if (value >= 7.0) return 'hyperglycemia'
  if (value >= 5.6) return 'prediabetes'
  return 'normal'
}

// 获取血糖数据
const fetchData = async () => {
  try {
    axios.get(`/health/getHealth/6/${currentPage.value}/${pageSize.value}`).then((response) => {
      console.log(response.data.data);
      total.value = response.data.total;
      tableData.value = response.data.data;
    })
  } catch (error) {
    ElMessage.error('获取数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

//查询
const handleQuery = () => {
  try {
    loading.value = true
    axios.post(`/health/getHealthData/${currentPage.value}/${pageSize.value}`, queryParams).then(response => {
      total.value = response.data.total;
      tableData.value = response.data.data;
    })
  } catch (error) {
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    userAccount: '',
    bloodSugarStatus: '0',
    beginBloodSugar: '0.0',
    endBloodSugar: '0.0',
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 查看记录
const viewRecords = (row) => {
  currentUser.id = row.userId
  currentUser.username = row.userAccount
  currentUser.nickname = row.userNickname
  recordDialogVisible.value = true
}

// 导出数据
const exportData = () => {
  location.href = `http://localhost:8080/health/download/1/${currentPage.value}/${pageSize.value}`;
  ElMessage.success('导出成功');
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="blood-sugar-management">
    <!-- 查询区域 -->
    <div class="query-area">
      <el-card shadow="hover">
        <el-form :model="queryParams" label-width="100px" :inline="true">
          <el-form-item label="用户账号">
            <el-input
                v-model="queryParams.userAccount"
                placeholder="请输入用户账号"
                clearable
            />
          </el-form-item>
          <el-col :span="6">
            <el-form-item label="血糖状态">
              <el-select
                  v-model="queryParams.bloodSugarStatus"
                  placeholder="请选择血糖状态"
                  clearable
              >
                <el-option
                    v-for="item in bloodSugarStatusTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item label="血糖范围">
            <el-input
                v-model="queryParams.beginBloodSugar"
                placeholder="最小值"
                style="width: 100px"
            /> -
            <el-input
                v-model="queryParams.endBloodSugar"
                placeholder="最大值"
                style="width: 100px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" :icon="Search">查询</el-button>
            <el-button @click="resetQuery" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据区域 -->
    <div class="data-area">
      <el-card shadow="hover">
        <div class="header">
          <h3>用户血糖数据统计</h3>
          <el-button type="primary" @click="exportData" :icon="Download">导出数据</el-button>
        </div>

        <el-table
            :data="tableData"
            border
            style="width: 100%"
            v-loading="loading"
        >
          <el-table-column prop="userAccount" label="用户账号" width="150" sortable>
            <template #default="{row}">
              <span>{{ row.userAccount }}</span>
              <el-tag :type="getBloodSugarStatus(row.bloodSugar).type" size="small">
                {{ getBloodSugarStatus(row.bloodSugar).label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="userNickname" label="用户昵称" width="150" />
          <el-table-column prop="bloodSugar" label="血糖值" width="150">
            <template #default="{row}">
              <span :class="getSugarClass(row.bloodSugar)">
                {{ row.bloodSugar.toFixed(1) }} mmol/L
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="lastMeasurementTime" label="最近测量时间" width="180" sortable />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{row}">
              <el-button
                  type="primary"
                  size="small"
                  @click="viewRecords(row)"
                  :icon="View"
              >查看记录</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[1,3,5,10, 20, 30, 50]"
          :small="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 血糖记录对话框 -->
    <el-dialog
        v-model="recordDialogVisible"
        :title="`血糖记录 - ${currentUser.nickname} (${currentUser.username})`"
        width="80%"
    >
      <user-blood-sugar-records
          v-if="recordDialogVisible"
          :user-id="currentUser.id"
      />
      <template #footer>
        <el-button @click="recordDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.blood-sugar-management {
  padding: 20px;
}

.query-area {
  margin-bottom: 20px;
}

.data-area {
  margin-bottom: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: flex-end;
}

.normal {
  color: var(--el-color-success);
  font-weight: bold;
}

.hypoglycemia {
  color: var(--el-color-warning);
  font-weight: bold;
}

.hyperglycemia {
  color: var(--el-color-danger);
  font-weight: bold;
}

.prediabetes {
  color: var(--el-color-warning);
  font-weight: bold;
}

.el-tag {
  margin-left: 8px;
}
</style>